package com.snowj.apaas.service.impl;

import com.snowj.apaas.security.SecurityUtils;
import com.snowj.apaas.web.vm.LoginVM;
import com.snowj.apaas.domain.auto.Users;
import com.snowj.apaas.repository.auto.UsersMapper;
import com.snowj.apaas.service.AuthService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
@Transactional
public class AuthServiceImpl implements AuthService {

    private final UsersMapper usersMapper;

    private final BCryptPasswordEncoder passwordEncoder;

    public AuthServiceImpl(UsersMapper usersMapper, BCryptPasswordEncoder passwordEncoder) {
        this.usersMapper = usersMapper;
        this.passwordEncoder = passwordEncoder;
    }

    /**
     * 修改密码
     *
     * @param loginVM 密码信息
     * @return 是否修改成功
     */
    @Override
    public boolean changePassword(LoginVM loginVM) {
        String login = loginVM.getUsername();
        Optional<Users> usersOptional = usersMapper.selectByPrimaryKey(login);
        if (usersOptional.isPresent()) {
            Users users = usersOptional.get();
            users.setPassword(passwordEncoder.encode(loginVM.getNewPassword()));
            usersMapper.updateByPrimaryKeySelective(users);
            return true;
        }
        return false;
    }


    /**
     * 修改密码
     *
     * @param loginVM 密码信息
     * @return 是否修改成功
     */
    @Override
    public boolean changeOwnPassword(LoginVM loginVM) {
        String login = SecurityUtils.getCurrentUserLogin();
        Optional<Users> usersOptional = usersMapper.selectByPrimaryKey(login);
        if (usersOptional.isPresent()) {
            Users users = usersOptional.get();
            users.setPassword(passwordEncoder.encode(loginVM.getNewPassword()));
            usersMapper.updateByPrimaryKeySelective(users);
            return true;
        }
        return false;
    }


    @Override
    public Optional<Users> currentUserInfo() {
        String login = SecurityUtils.getCurrentUserLogin();
        return usersMapper.selectByPrimaryKey(login);
    }
}
